<template>
  <div
    :class="className"
    :style="{height: height, width: width}"
  />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import ResizeMixin from './mixins/resize'


const animationDuration = 6000

export default {
  name: 'IotBarChart',
  mixins: [ResizeMixin],
  props: {
    className: {
      default: 'chart'
    },
    width: {
      default: '100%'
    },
    height: {
      default: '300px'
    },
    chartData: {
      default: function() {
        return []
      }
    }
  },
  watch: {
    chartData: function(value, oldVal) {
      this.$nextTick(() => {
        this.initChart()
      })
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      let data = this.chartData

      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        tooltip: {
          formatter: function(param) {
            param = param[0]
            return ` ${param['name']}<br/> <span style="color:#ff5757;">●</span> ${(data).nameList[(param).dataIndex]} : ${(param).value}`
          },
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              width: 0
            }
          },
          backgroundColor: 'rgb(255, 255, 255, 0.8)',
          shadowColor: 'rgb(0, 0, 0, 0.8)',
          shadowBlur: 10,
          padding: 10,
          textStyle: {
            color: '#666'
          },
          extraCssText: 'box-shadow: 0 0 10px rgba(150, 150, 150, 0.4)'
        },
        grid: {
          left: 10,
          right: 30,
          bottom: 20,
          top: 20,
          containLabel: true
        },
        xAxis: [{
          type: 'value',
          axisTick: {
            alignWithLabel: true
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            },
            show: true
          }
        }],
        yAxis: [
          {
            type: 'category',
            data: (this.chartData).YData,
            lineStyle: {
              type: 'dashed'
            }
          }
        ],
        series: [
          {
            name: '',
            type: 'bar',
            barCategoryGap: '8',
            barWidth: '35%',
            itemStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(
                  1, 0, 0, 0,
                  [
                    { offset: 0, color: '#FF5555' },
                    { offset: 1, color: '#FF7E62' }
                  ]
                )
              }
            },
            data: (this.chartData).XData,
            animationDuration
          }
        ]
      })
    }
  }
}
</script>
